﻿using AntdUI;
using Super.Admin.Global;
using Super.Admin.IServices;
using Super.Admin.Mappers;
using Super.Admin.Models.Department;
using Super.Admin.Models.Role;
using Super.Admin.Models.User;
using Super.Admin.Utils;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Views.Base;
using Super.Admin.Views.Main;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace Super.Admin.Views.Page
{
    public partial class UserManagementView : BaseUserControl
    {
        private readonly IUserService _userService;
        private readonly IUserOperateLogService _userOperateLogService;
        private readonly IRoleService _roleService;
        private readonly IDepartmentService _departmentService;
        private List<CellButton> _cellButtons = new List<CellButton>();
        private List<RoleBaseModel> RoleModels = new List<RoleBaseModel>();
        private List<DepartmentDetailModel> _departmentModels = new List<DepartmentDetailModel>();

        private bool _isLoad = false;
        public UserManagementView(IUserService userService, IUserOperateLogService userOperateLogService, IRoleService roleService, IDepartmentService departmentService)
        {
            InitializeComponent();
            InitializeAuthPermissionList();
            this.Load += UserManagementView_Load;
            _userService = userService;
            _userOperateLogService = userOperateLogService;
            _roleService = roleService;
            _departmentService = departmentService;
        }

        private void UserManagementView_Load(object? sender, EventArgs e)
        {
            _isLoad = true;
            InitializeControls();

            TableUserModel.Columns = new AntdUI.ColumnCollection
            {
                new AntdUI.ColumnCheck("Check"),
                new AntdUI.Column("Index","序号",ColumnAlign.Center).SetFixed().SetWidth("80"),
                new AntdUI.Column("UserId","用户ID",ColumnAlign.Center).SetFixed().SetWidth("80").SetSortOrder(true),
                new AntdUI.Column("GravatarImage","头像",ColumnAlign.Center).SetFixed().SetWidth("80"),
                new AntdUI.Column("UserName","用户名", ColumnAlign.Center).SetFixed().SetWidth("100").SetSortOrder(true),
                new AntdUI.Column("GenderTag","性别", ColumnAlign.Center).SetFixed().SetWidth("80").SetSortOrder(true),
                new AntdUI.Column("NickName","昵称", ColumnAlign.Center).SetFixed().SetWidth("220").SetSortOrder(true),
                new AntdUI.Column("Phone","手机号", ColumnAlign.Center).SetFixed().SetWidth("120").SetSortOrder(true),
                new AntdUI.Column("Email","邮箱", ColumnAlign.Center).SetFixed().SetWidth("180").SetSortOrder(true),
                new AntdUI.Column("IsActiveTag","用户状态", ColumnAlign.Center).SetFixed().SetWidth("80").SetSortOrder(true),
                new AntdUI.Column("DepartmentName","部门", ColumnAlign.Center).SetFixed().SetWidth("100").SetSortOrder(true),
                new AntdUI.Column("UserRoleTags","角色", ColumnAlign.Center).SetFixed().SetWidth("300").SetLineBreak(true),
                new AntdUI.Column("Operates","操作", ColumnAlign.Center).SetFixed(),
            };

            LoadRoles();
            LoadDepartments();
            _isLoad = false;
        }

        private void InitializeAuthPermissionList()
        {
            BtnCreate.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.UserCreate);
            BtnSerach.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.UserSearch);
            BtnBatchDelete.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.UserBatchDelete);

            // 单元格按钮
            _cellButtons.Clear();
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.UserUpdate))
            {
                _cellButtons.Add(new CellButton(PermissionKeys.UserUpdate, "编辑", TTypeMini.Primary) { });
            }
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.UserDelete))
            {
                _cellButtons.Add(new CellButton(PermissionKeys.UserDelete, "删除", TTypeMini.Error) { });
            }
        }

        public override void DoRefresh()
        {
            BtnSerach.PerformClick();
        }

        private void LoadDepartments()
        {
            _departmentModels = _departmentService.GetDepartments().ToDetailModels().ToList();
        }

        private void LoadRoles()
        {
            RoleModels = _roleService.GetRoles().ToBaseModels().ToList();
        }

        // 初始化 重置参数
        private void InitializeControls()
        {
            TxtUserName.Text = "";
            TxtNickName.Text = "";
            TxtPhone.Text = "";
            TxtEmail.Text = "";

            CmbGender.Items.Clear();
            CmbGender.Items.AddRange(new AntdUI.ISelectItem[] { new AntdUI.SelectItem("女", 0), new AntdUI.SelectItem("男", 1) });
            CmbGender.SelectedIndex = -1;
            CmbStatus.Items.Clear();
            CmbStatus.Items.AddRange(new AntdUI.ISelectItem[] { new AntdUI.SelectItem("启用", 0), new AntdUI.SelectItem("停用", 1) });
            CmbStatus.SelectedIndex = -1;

            Pagination.PageSizeOptions = new int[] { 10, 20, 30, 50, 100 };
            Pagination.Current = 1;
        }

        private void PnlSearch_ExpandChanged(object sender, AntdUI.CollapseExpandEventArgs e)
        {
            GridMain.SuspendLayout();
            if (e.Expand)
            {
                GridMain.Span = "160:100%;10:100%;100%:100%";
            }
            else
            {
                GridMain.Span = "47:100%;10:100%;100%:100%";
            }
            GridMain.ResumeLayout();
        }
        private void BtnReset_Click(object sender, EventArgs e)
        {
            InitializeControls();
        }

        private void BtnCreate_Click(object sender, EventArgs e)
        {
            Drawer.Config config = new Drawer.Config(ParentForm, new UserManagementModify(ParentForm, new UserDetatilModel(), RoleModels, _departmentModels, _userService, _userOperateLogService, "新增用户") { Width = 400 })
            {
                Align = TAlignMini.Right
            };
            config.OnClose = () =>
            {
                DoRefresh();
            };
            config.open();
        }

        private void BtnSerach_Click(object sender, EventArgs e)
        {
            try
            {
                int gender = -1;
                if (CmbGender.SelectedValue != null && CmbGender.SelectedIndex != -1)
                {
                    gender = Convert.ToInt32(CmbGender.SelectedValue);
                }
                int status = -1;
                if (CmbStatus.SelectedValue != null && CmbStatus.SelectedIndex != -1)
                {
                    status = Convert.ToInt32(CmbStatus.SelectedValue);
                }
                var userEntities = _userService.GetUsers(TxtUserName.Text, gender, TxtNickName.Text, TxtPhone.Text, TxtEmail.Text, status, Pagination.PageSize, Pagination.Current, out int totalCount);
                Pagination.Total = totalCount;
                var userModels = userEntities.ToDetailModels().ToList();
                if (userModels.Count == 0 && totalCount != 0)
                {
                    Pagination.Current = 0;
                    return;
                }
                foreach (var user in userModels)
                {
                    // 索引
                    user.Index = ((Pagination.Current - 1) * (int)Pagination.PageSize) + userModels.IndexOf(user) + 1;
                    // 按钮
                    user.Operates = TableHelper.CopyCellButton(_cellButtons).ToArray();
                    // 角色
                    List<CellTag> roleTags = new List<CellTag>();
                    foreach (var role in user.UserRoles)
                    {
                        roleTags.Add(new CellTag(role.Role.Name, TTypeMini.Primary));
                    }
                    user.UserRoleTags = roleTags.ToArray();
                    // Image
                    if (!string.IsNullOrEmpty(user.Gravatar) && File.Exists(user.Gravatar))
                    {
                        user.GravatarImage = new CellImage[]
                        {
                             new CellImage(Bitmap.FromFile(user.Gravatar),80){ BorderWidth = 0 },
                        };
                    }
                }
                TableUserModel.DataSource = userModels;
                _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"用戶管理搜索", "system:user:search");
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(ParentForm, ex.Message);
            }
        }

        private void Pagination_ValueChanged(object sender, PagePageEventArgs e)
        {
            if (_isLoad) return;
            DoRefresh();
        }

        private string Pagination_ShowTotalChanged(object sender, PagePageEventArgs e)
        {
            return $"{e.PageSize} / {e.Total}条 {e.PageTotal}页";
        }

        private void TableUserModel_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is UserDetatilModel model)
            {
                if (e.Btn.Id == PermissionKeys.UserDelete)
                {
                    var result = AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "是否删除", new AntdUI.Modal.TextLine[]
                    {
                        new Modal.TextLine(model.UserIdAndUserName,AntdUI.Style.Db.Primary),
                    }, AntdUI.TType.Error)
                    {
                        CancelText = "取消",
                        OkType = TTypeMini.Error,
                        OkText = "删除"
                    });
                    if (result == DialogResult.OK)
                    {
                        _userService.DeleteUser(model.UserId);
                        _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"用戶管理删除：【{model.UserName}】", "system:user:batchdelete");
                        AntdUI.Message.success(ParentForm, "删除成功");
                        DoRefresh();
                    }
                }
                else if (e.Btn.Id == PermissionKeys.UserUpdate)
                {
                    Drawer.Config config = new Drawer.Config(ParentForm, new UserManagementModify(ParentForm, model, RoleModels, _departmentModels, _userService, _userOperateLogService, "编辑用户") { Width = 400 })
                    {
                        Align = TAlignMini.Right
                    };
                    config.OnClose = () =>
                    {
                        DoRefresh();
                    };
                    config.open();
                }
            }
        }

        private void BtnBatchDelete_Click(object sender, EventArgs e)
        {
            // 删除选中的 
            List<UserDetatilModel> models = TableUserModel.DataSource as List<UserDetatilModel>;
            List<UserDetatilModel> selectModels = models.Where(m => m.Check).ToList();
            try
            {
                if (selectModels.Count == 0) return;
                string nameList = "";
                foreach (var name in selectModels)
                {
                    nameList += name.UserName + ",";
                }
                var result = AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "是否删除", new AntdUI.Modal.TextLine[]
                {
                    new Modal.TextLine(nameList.TrimEnd(','),AntdUI.Style.Db.Primary),
                }, AntdUI.TType.Error)
                {
                    CancelText = "取消",
                    OkType = TTypeMini.Error,
                    OkText = "删除"
                });
                if (result == DialogResult.OK)
                {
                    foreach (var model in selectModels)
                    {
                        _userService.DeleteUser(model.UserId);
                    }
                    _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"用戶管理批量删除：【{nameList.TrimEnd(',')}】", "system:user:batchdelete");
                    AntdUI.Message.success(ParentForm, "删除成功");
                    DoRefresh();
                }
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(ParentForm, "删除失败：" + ex.Message);
            }
        }
    }
}
